package com.cakemallproject.controller;

import com.cakemallproject.pojo.Result;
import com.cakemallproject.pojo.mapperObj.Type;
import com.cakemallproject.service.TypeService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.List;

@Slf4j
@RestController
@RequestMapping("/type")
public class TypeController {
    @Autowired
    private TypeService typeService;

    @GetMapping
    public Result list() {
        return Result.success(typeService.list());
    }

    @GetMapping("/{tid}")
    public Result getByTid(@PathVariable Integer tid) {
        log.info("查询类别：{}",tid);
        Type type = typeService.getById(tid);
        return Result.success(type);
    }

    @PostMapping
    public Result insert(@RequestBody Type type) {
        log.info("添加类别：{}",type);
        try {
            typeService.insert(type);
        } catch (RuntimeException e) {
            return Result.error("name_exist");
        }
        return Result.success();
    }

    @DeleteMapping("/{ids}")
    public Result delete(@PathVariable List<Integer> ids) {
        log.info("删除类型：{}",ids);
        typeService.delete(ids);
        return Result.success();
    }

    @PutMapping
    public Result update(@RequestBody Type type) {
        log.info("修改类别：{}",type);
        try {
            typeService.update(type);
        } catch (RuntimeException e) {
            return Result.error("name_exist");
        }
        return Result.success();
    }
}
